package net.wanho.controller;

import lombok.RequiredArgsConstructor;
import net.wanho.dto.RoleAuthDTO;
import net.wanho.entity.Role;
import net.wanho.service.RoleAuthService;
import net.wanho.service.RoleService;
import net.wanho.vo.AjaxResult;
import org.springframework.web.bind.annotation.*;

@RestController
@RequiredArgsConstructor
@RequestMapping("/role")
public class RoleController {
    private final RoleService roleService;
    private final RoleAuthService roleAuthService;

    /**
     *  角色列表
     */
    @GetMapping("/role-list")
    public AjaxResult roleList(){
        return AjaxResult.success(roleService.list());
    }

    /**
     *  角色分页列表
     */
    @GetMapping("/role-page-list")
    public AjaxResult rolePageList(Role role,
                                   @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                   @RequestParam(required = false, defaultValue = "5") Integer pageSize){
        return AjaxResult.success(roleService.rolePage(role, pageNum,pageSize));
    }

    /**
     *  添加角色
     */
    @PostMapping("/role-add")
    public AjaxResult roleAdd(@RequestBody Role role){
        roleService.addRole(role);
        return AjaxResult.success(null, "角色添加成功！");
    }

    /**
     *  修改角色状态
     */
    @PutMapping("/role-state-update")
    public AjaxResult roleStateUpdate(@RequestBody Role role){
        roleService.updateRoleById(role);
        return AjaxResult.success(null, "修改成功！");
    }

    /**
     *  根据Id查询角色
     */
    @GetMapping("/{id}")
    public AjaxResult getRoleById(@PathVariable Integer id){
        return AjaxResult.success(roleService.getRoleById(id));
    }

    /**
     *  编辑角色信息
     */
    @PutMapping("/role-update")
    public AjaxResult roleUpdate(@RequestBody Role role){
        roleService.updateRoleById(role);
        return AjaxResult.success(null, "角色修改成功！");
    }

    /**
     *  删除角色
     */
    @DeleteMapping("/role-delete/{id}")
    public AjaxResult roleDelete(@PathVariable Integer id){
        roleService.removeById(id);
        return AjaxResult.success(null, "角色删除成功！");
    }

    /**
     *  根据角色Id查询权限
     */
    @GetMapping("/role-auth")
    public AjaxResult roleAuth(Integer roleId){
        return AjaxResult.success(roleAuthService.getUserRoleListById(roleId));
    }

    /**
     *  更改角色的权限
     */
    @PutMapping("/auth-grant")
    public AjaxResult authGrant(@RequestBody RoleAuthDTO roleAuthDTO){
        roleAuthService.updateRoleAuth(roleAuthDTO);
        return AjaxResult.success(null, "分配权限成功！");
    }

    @GetMapping("/exportTable")
    public AjaxResult exportTable(Role role,
                                  @RequestParam(required = false, defaultValue = "1") Integer pageNum,
                                  @RequestParam(required = false, defaultValue = "5") Integer pageSize){
        return AjaxResult.success(roleService.exportTable(role, pageNum, pageSize));
    }
}
